package com.lanyou.esb.web.serviceMonitor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.esb.service.IfResTimeService;
import com.lanyou.esb.vo.IfResTimeVo;
import com.lanyou.esb.vo.IfResTimeVo.IfGroup;
import com.lanyou.esb.web.param.IfResTimeParam;

/**
 * 服务响应时间控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/ifResTime")
public class IfResTimeController {
	@Autowired
	IfResTimeService ifResTimeService;

	@Autowired
	UserSessionService userSessionService;

	/**
	 * 获取服务响应时间
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/search/findIfResTimeInfo")
	public Page<IfResTimeVo.IfGroup> findIfResTimeInfo(IfResTimeParam param,
			Pageable pageable) throws Exception {
		if (StringUtils.isBlank(param.getPeriod())) {
			// 至少要选择一个种周期
			return new PageImpl<IfResTimeVo.IfGroup>(new ArrayList<>(0),
					pageable, 0);
		}

		if (StringUtils.isNotBlank(param.getIfName())) {
			param.setIfName("%" + param.getIfName() + "%");
		}
		IfResTimeVo vo = ifResTimeService.findIfResTimeInfo(param, pageable);
		format(vo.getIfGroups());
		Page<IfResTimeVo.IfGroup> page = new PageImpl<IfResTimeVo.IfGroup>(
				vo.getIfGroups(), pageable, vo.getTotal());
		return page;
	}

	/**
	 * 响应时间保留三位小数
	 * 
	 * @param ifGroups
	 */
	private void format(List<IfGroup> ifGroups) {
		for (IfGroup group : ifGroups) {
			// 总平均响应时间
			BigDecimal b = new BigDecimal(group.getAvg());
			group.setAvg(b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());
			// 总最大响应时间
			b = new BigDecimal(group.getMax());
			group.setMax(b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());
			// 引擎平均响应时间
			b = new BigDecimal(group.getEsbAvg());
			group.setEsbAvg(b.setScale(3, BigDecimal.ROUND_HALF_UP)
					.doubleValue());
			// 引擎最大响应时间
			b = new BigDecimal(group.getEsbMax());
			group.setEsbMax(b.setScale(3, BigDecimal.ROUND_HALF_UP)
					.doubleValue());
		}
	}

}
